<?php


namespace App\controllers\admin;


use App\controllers\Base;
use App\models\CustomerSession;
use Consts\RedisKey;
use Helper\Output;
use Helper\Mysql;
use Helper\Redis;
use Helper\Reg;
use App\models\FdManager;


class Session extends Base
{


    /**
     * 获取在线客户
     * @param $request
     * @param $response
     */
    public function index($request, $response){

        $online_customers = Redis::getInstance()->hValS(RedisKey::online_customer_list($this->getUserId()));
        if($online_customers){

            foreach ($online_customers as &$item){
                $item = json_decode($item,true);
                //查询未读消息条数
                $count = Mysql::getInstance()
                    ->where('session_id',$item['sessid'])
                    ->where('send_user_type',2)
                    ->where('is_read',0)
                    ->getValue('user_chat_record','count(*)');
                $item['unread_count'] = $count;
            }
        }else{

            $sess = Mysql::getInstance()
                ->where('auid',$this->getUserId())
                ->where('end_at',0)
                ->get('customer_session',null,'id as sessid,uid,create_at');
//            var_dump('$sess',$sess);
//            var_dump('sql',Mysql::getInstance()->getLastQuery());
            if(!$sess){
                $online_customers = [];
            }else{
                foreach ($sess as &$item){

                    $item['user'] = Mysql::getInstance()
                        ->where('id',$item['uid'])
                        ->getOne('customer');
                    //查询未读消息条数
                    $count = Mysql::getInstance()
                        ->where('session_id',$item['sessid'])
                        ->where('send_user_type',2)
                        ->where('is_read',0)
                        ->getValue('user_chat_record','count(*)');
                    $item['unread_count'] = $count;
                }
                $online_customers = $sess;
            }

        }


        return Output::json(200,'',$online_customers);

    }

    /**
     * 获取排队中的客户
     * @param $request
     * @param $response
     *
     */
    public function getQueueCustomer($request, $response){

        $ids = Redis::getInstance()->zRange(RedisKey::service_queue_list($this->getUserId()),0,-1);
        $customers = [];
        if($ids){
            $customers = Mysql::getInstance()->where('id',$ids ,'in')->get('customer');
        }
        return  Output::json(200,'',$customers);
    }


    /**
     * 获取历史消息
     * @param $server
     * @param $fd
     * @param $param
     * @throws \Exception
     */
    public function getHistoryMessge($request, $response){
        $page = $request->post['page']?:1;
        $pagesize = $request->post['page_size']?:20;
        $sessid = $request->post['sessid'];

        $list = Mysql::getInstance()
                ->where('session_id',$sessid)
                ->orderBy('create_at','desc')
                ->get('user_chat_record',[($page-1)*$pagesize,$pagesize]);

        $total = Mysql::getInstance()->where('session_id',$sessid)->getValue('user_chat_record','count(*)');

        return Output::json(200,['list'=> $list ,'total'=> $total]);


    }


    /**
     * 发送消息
     * @param $server
     * @param $fd
     * @param $param
     * @throws \Exception
     */
    public function sendMsg($request, $response){

        $param =  $request->post;
        $sessid = $param['sessid'];

        \App\models\Session::pushChatMessage($sessid ,$this->getUserId() ,$param['accept_uid'] ,$param['content'],2000,$param['type']);

        return  Output::json(200);

    }

    /**
     * 会话消息设置为已读
     * @param $request
     * @param $response
     * @return false|string
     * @throws \Exception
     */
    public function setRead($request, $response){

        $res = Mysql::getInstance()
            ->where('session_id',$request->post['sessid'])
            ->where('accept_uid',$this->getUserId())
            ->where('is_read',0)
            ->update('user_chat_record',['is_read'=> 1]);

//        var_dump(Mysql::getInstance()->getLastQuery());


        if($res){
            return Output::json(200);
        }else{
            return Output::json(400);
        }

    }


    /**
     * 结束会话
     * @param $request
     * @param $response
     * @return false|string
     * @throws \Exception
     */
    public function close($request, $response){

        $param = $request->post;
        $sess = Mysql::getInstance()->where('id',$param['sessid'])->where('end_at',0)->getOne('customer_session');
        if(!$sess){

            return Output::json(1017);
        }
        $data = [
            'end_at' => time(),
            's' => time()-$sess['create_at']
        ];
        Mysql::getInstance()->where('id',$param['sessid'])->update('customer_session',$data);
        //取出第一位排队者进行会话
        $uids = Redis::getInstance()->zRange(RedisKey::service_queue_list($this->getUserId()),0,0);
        if($uids){
             CustomerSession::createSession( $this->getUserId() ,$uids[0]);

             Redis::getInstance()->zRem(RedisKey::service_queue_list($this->getUserId()),$uids[0]);
             //推送所有排队的用户新排名
             $pushuids = Redis::getInstance()->zRange(RedisKey::service_queue_list($this->getUserId()),0,-1);
             foreach ($pushuids as $k=>  $uid){
                 Reg::getInstance()->get('server')->push(FdManager::getFdByUid($uid) ,Output::json(2002,['queue_num'=> $k+1]));
             }

        }
        //移除会话
        Redis::getInstance()->hDel(RedisKey::online_customer_list($this->getUserId()) ,'uid:'.$param['uid'] ,$param['uid']);

        //断开用户连接
        Reg::getInstance()->get('server')->disconnect($this->getFdByUid($param['uid']));
        return Output::json(200);
    }


    /**
     * 上传聊天图片
     * @param $request
     * @param $response
     * @return false|string
     */
    public function uploadImg($request, $response)
    {
        if(!isset($request->files)){

            return Output::json(1028);
        }

        $file_name = parent::uploadImgs($request);
        if(!$file_name){

            return  Output::json(400);
        }
        return  Output::json(200 ,['file_name'=> $file_name ]);

    }


    /**
     * 上传聊天视频
     * @param $request
     * @param $response
     * @return false|string
     */
    public function uploadVideo($request, $response)
    {
        if(!isset($request->files)){

            return Output::json(1028);
        }

        $file_name =  parent::uploadVideos($request);
        if(!$file_name){

            return  Output::json(400);
        }
        return  Output::json(200 ,['file_name'=> $file_name ]);

    }





}